from fastapi import FastAPI, Request, UploadFile, File
from fastapi.responses import HTMLResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
import os
from pydantic import BaseModel
from ocr import imageText
import shutil
import random

app = FastAPI()

# 加载静态文件
app.mount("/static", StaticFiles(directory="static"), name="static")


def remove_file(path: str):
    if os.path.exists(path):
        os.remove(path)  # 删除文件


class Params(BaseModel):
    content: str
    type: str


# 测试的POST请求
@app.post("/identify")
async def create_upload_file(file: UploadFile = File(...)):
    # 将上传的文件保存到服务器的临时目录
    file_location = f"temp/{file.filename+ random.randint(0, 100000000)}"
    with open(file_location, "wb") as buffer:
        shutil.copyfileobj(file.file, buffer)

    detectionResult = imageText(file_location)
    # 删除临时文件，如果不需要可以跳过这一步
    os.remove(file_location)

    # 将识别结果返回给客户端
    return detectionResult


# GET请求加载index.html文件
@app.get("/", response_class=HTMLResponse)
async def read_index(request: Request):
    with open(os.path.join("static", "index.html"), "r") as f:
        html_content = f.read()
    return HTMLResponse(content=html_content, status_code=200)


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=8000)
